<?php
/**
 * 微信支付
 * Created by PhpStorm.
 * User: qinzhi
 * Date: 2017/7/5
 * Time: 14:12
 */

class Service_WxPay{

    const API_URL = 'http://pay.lanrenyuehui.com/wxgzhpay/wxgzhpay2';

    const PARA_ID = '10908';

    const APP_ID = '10952';

    const KEY = '2d59b3e42412ef6ed5bc28968dcffdb2';

    /**
     * 创建支付订单
     * @param $order_no string 订单号
     * @param $total_fee int 支付金额(元)
     * @param $openid string 用户微信openid
     * @param $body string
     * @param $notify_url string 通知地址
     * @param $callback_url string 跳转地址
     * @param string $attach 附加数据
     * @return string|array json数据
     */
    public static function create_order($order_no,$openid,$total_fee,$body,$notify_url,$callback_url,$attach=''){
        $sign = strtolower(md5(self::PARA_ID.self::APP_ID.$order_no.$total_fee.self::KEY));
        $data = array(
            'body' => $body,
            'total_fee' => $total_fee,
            'para_id' => self::PARA_ID,
            'app_id' => self::APP_ID,
            'order_no' => $order_no,
            'notify_url' => $notify_url,
            'callback_url' => $callback_url,
            'type' => 1,
            'sub_openid' => $openid,
            'attach' => $attach,
            'sign' => $sign,
        );
        //var_dump($data);
        $post_str = self::buildParam($data);
        $result = self::http_post_data(self::API_URL,$post_str);
        $result = json_decode($result,true);
        return $result;
        /*echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        printf_info($order);*/
    }

    /**
     * 通知
     *  {"pay_type":"0",
     *   "wxno":"4009782001201707140755423233",
     *   "app_id":"10952",
     *   "orderno":"2017071417350142301",
     *   "fee":"1",
     *   "token":"f0e85dc0836ab723768b9e85ff7378bf",
     *   "sign":"73ef1506ac74a138f54f6b6b7b5aab58",
     *   "attach":""}
     */
    public static function notify_url(){
        $orderno = FRequest::getString('orderno');      //订单号
        $wxno = FRequest::getString('wxno');    //支付流水号
        $fee = FRequest::getInt('fee');     //订单金额
        $sign = FRequest::getString('sign');    //签名
        $pay_type = FRequest::getInt('pay_type');   //0微信 1支付宝
        $appid = FRequest::getString('appid');      //商户信息产品ID
        $attach = FRequest::getString('attach');    //自定义参数

        FLogger::write($_REQUEST,'wxpay_notify');

        if(self::checkSign($orderno,$fee,$sign)){
            $ordersT = new FTable('orders','','xhs_slave');
            $order = $ordersT->where(array('o_id'=>$orderno))->find();

            if($order['status'] == 1){
                $ordersT = new FTable('orders','','xhs_master');
                $ordersT->where(array('o_id'=>$orderno))->update1(array('status'=>2,'p_id'=>$wxno,'pay_time'=>date('Y-m-d H:i:s')));

                Service_Order::orderPushQueue($orderno,$order['shop_id']);
                $productT = new FTable('orders_product','','xhs_slave');
                $productList = $productT->where(array('o_id'=>$orderno))->select();
                $pidList = array();
                foreach ($productList as $product){
                    $paynum = $product['paynum'];
                    $whereStr = '';
                    if(in_array($product['pid'],$pidList) === false){
                        $whereStr = ',`paynum`=`paynum`+1';
                        $pidList[] = $product['pid'];
                    }
                    FDB::query("UPDATE goods SET `cs_num`=`cs_num`+{$paynum}{$whereStr} WHERE auto_id={$product['gid']}",'xhs_master');
                }

                Service_Template::set_tpl_msg($orderno); //发通知

                echo 'ok';
                exit;
            }else{
                FLogger::write($order,'wxpay_notify');
                FLogger::write('订单已支付!','wxpay_notify');
            }
        }else{
            FLogger::write('验签失败!','wxpay_notify');
        }
        echo 'fail';
        exit;
    }

    /**
     * 验证签名
     * @param $order_no
     * @param $fee
     * @param $sign
     * @return bool
     */
    public static function checkSign($order_no,$fee,$sign){
        if(strtolower(md5($order_no.$fee.self::KEY)) == $sign){
            return true;
        }else{
            return false;
        }
    }

    public static function buildParam($post_data){
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ) . "&" ;
        }
        $post_data = substr($o,0,-1);
        return $post_data;
    }

    public static function http_post_data($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 200);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $res = curl_exec($ch);
        if ($res == NULL) {
            curl_close($ch);
            return false;
        }
        curl_close($ch);
        return $res;
    }
}
